package com.flyqiu.flow.core.impl;

import com.flyqiu.flow.api.std.FlyQiuFlowObjectFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
public class DefaultFlowObjectFactory implements FlyQiuFlowObjectFactory {
    private final Map<String, Constructor> cache = new HashMap<>();

    @Override
    public <T> T createObject(Class<T> clazz) {
        Constructor<T> classConstructor = getClassConstructor(clazz);
        try {
            return classConstructor.newInstance();
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    private <T> Constructor<T> getClassConstructor(Class<T> clazz) {
        String name = clazz.getName();
        if (cache.containsKey(name)) {
            return cache.get(name);
        }
        try {
            Constructor<T> constructor = clazz.getConstructor();
            cache.put(name, constructor);
            return constructor;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}
